package com.chen.framework.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.root.entity.AuthUser;
import com.chen.root.oclass.dto.UserInfoDTO;
import com.chen.root.oclass.vo.LoginVO;
import com.chen.base.utils.ConvertUtil;
import com.chen.framework.mapper.AuthUserMapper;
import com.chen.framework.service.inter.AuthUserService;
import com.chen.framework.service.inter.AuthLinkUserRoleService;
import com.chen.root.base.R;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ChenJinLong
 * @since 2023-05-21
 */
@Service
@AllArgsConstructor
public class AuthUserServiceImpl extends ServiceImpl<AuthUserMapper, AuthUser> implements AuthUserService {

    private final AuthLinkUserRoleService authLinkUserRoleService;

    @Override
    public R<UserInfoDTO> userInfo(LoginVO params) {
        AuthUser user = getOne(
                Wrappers.lambdaQuery(AuthUser.class).eq(AuthUser::getUsername, params.getUsername())
        );
        return R.ok(buildUserInfoDTO(user));
    }

    @Override
    public R<UserInfoDTO> userInfoByPhone(LoginVO params) {
        AuthUser user = getOne(
                Wrappers.lambdaQuery(AuthUser.class).eq(AuthUser::getPhone, params.getPhone())
        );
        return R.ok(buildUserInfoDTO(user));
    }

    private UserInfoDTO buildUserInfoDTO(AuthUser user){
        UserInfoDTO dto = null;
        if (user != null){
            dto = ConvertUtil.convertor(user, UserInfoDTO.class);
            List<String> authorities = authLinkUserRoleService.authoritiesListByUserId(user.getUserId());
            dto.setAuthoritiesList(authorities);
        }

        return dto;
    }
}
